<template>
	<view class="uni-page">
		<cu-custom :isBack="true">
			<block class="bar-font" slot="backText">设备配网</block>
		</cu-custom>
		<view class="page-main">
			<u-steps :list="numList" mode="number" :current="stepValue"></u-steps>
			<view class="main-box">
				<view class="imgs">
					<image src="/static/wifi.png" mode="" class="center_img"></image>
				</view>
				<view class="gundong">
					<view v-if="currents == 0">
						<u-loading mode="flower" size="56"></u-loading>
					</view>
					<view v-else-if="currents == 1">
						<u-icon name="checkmark-circle" size="48" color="#18b566" class="iconst"></u-icon>
					</view>
					<view v-else-if="currents == 2">
						<u-icon name="close-circle" size="48" color="#f29100" class="iconste"></u-icon>
					</view>
					<view class="msg">{{content}}</view>
				</view>
				<view class="buttonst">
					<u-button v-if="currents == 2" type="primary" shape="circle" class="back-btn"
						@click="linkToWifiForm">重新填写家庭Wi-Fi</u-button>
					<u-button type="primary" shape="circle" plain @click="linkToHome">返回首页</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const errEnum = {
		12000: '未先调用 startWifi 接口',
		12001: '当前系统不支持相关能力',
		12002: '密码错误',
		12003: '连接超时, 仅 Android 支持',
		12004: '重复连接 Wi-Fi',
		12005: 'Android 特有，未打开 Wi-Fi 开关',
		12006: 'Android 特有，未打开 GPS 定位开关',
		12007: '用户拒绝授权链接 Wi-Fi',
		12008: '无效 SSID',
		12009: '系统运营商配置拒绝连接 Wi-Fi',
		12010: '系统其他错误，需要在 errmsg 打印具体的错误原因',
		12011: '应用在后台无法配置 Wi-Fi',
		12013: '系统保存的 Wi-Fi 配置过期，建议忘记 Wi-Fi 后重试，仅 Android 支持',
		12014: 'iOS 特有，无效的 WEP / WPA 密码'
	}
	export default {
		data() {
			return {
				currents: 0,
				result: '',
				buttons: '下一步',
				ind: '',
				jinyong: true,
				targetWifiInfo: {
					SSID: '',
					password: '',
				},
				content: '正在配网（请将设备靠近路由器）……',
				sdk: {},
				accessToken: '',
				bindDeviceToken: '',
				deviceInfo: {
					mac: null
				},
				sendRerty: {
					times: 5
				}
			}
		},
		onShow() {
			// 延迟调用配网
			// uni.setTimeout(this.airkiss(), 10000)
		},
		destroyed() {
			wx.stopWifi()
			uni.stopWifi()
		},
		onLoad(options) {
			// 路由器的账号密码
			this.targetWifiInfo = {
				SSID: options.wifiName,
				password: options.pwd
			}
			// 设备的mac地址
			this.deviceInfo.mac = options.mac
			this.startWifi()
			this.connectWifi()
		},
		methods: {
			async startWifi() {
				console.log('开始wifi接口');
				const cRes = await new Promise((resolve, reject) => {
					wx.startWifi({
						success: (res) => {
							resolve(res)
							this.content = 'WiFi模块已启用，正在连接设备热点'
							return cRes
						},
						fail: (err) => {
							reject()
						}
					})
				});
			},
			async connectWifi() {
				const $t = this
				const cRes = await new Promise((resolve, reject) => {
					// 连接wifi
					wx.connectWifi({
						SSID: 'z_' + this.deviceInfo.mac,
						forceNewApi: true,
						password: 'z_123456',
						success: (res) => {
							$t.connectUDP()
							$t.sendDataUDP()
							resolve(res)
						},
						fail: (err) => {
							if (err.errCode && err.errCode == 12005) {
								uni.showModal({
									content: '请先打开手机 Wi-Fi 开关',
									showCancel: false
								});
							} else {
								let errMsg = ''
								if (!err.errCode) {
									errMsg = err.errMsg
								} else {
									errMsg = errEnum[err.errCode]
								}
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								});
							}
							setTimeout(uni.navigateBack({
							}), 1000)
							reject()
						}
					})
				});
				this.content = '设备热点连接成功'
				return cRes
			},
			async connectUDP() {
				// 建立udp连接
				const $t = this
				this.udp = wx.createUDPSocket()
				if (this.udp === null) {
					console.log('暂不支持')
					return;
				}
				this.udp.connect({
					address: '192.168.4.1',
					port: 8266
				})
				this.udp.bind()
				this.udp.onListening(function(res4) {
					console.log('4监听中...')
					console.log(res4)
				})
				this.udp.onMessage(res3 => {
					console.log('3监听中...')
					console.log(res3);
					// 这里解析，如果设备返回通过，那么就将重试次数直接置为0
					const unit8Arr = new Uint8Array(res3.message)
					// const base64 = wx.arrayBufferToBase64(unit8Arr)
					let encodedString = String.fromCharCode.apply(null, unit8Arr);
					// decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
					console.log(encodedString);
					// 需要将字符串解析成json，判断json：2、成功；3、解析错误；31、前一次的错误
					const recJson = JSON.parse(encodedString)
					if (recJson.cmdType && recJson.cmdType==2) {
						$t.currents = 1
						$t.content = '设备已配网'
						$t.sendRerty.times == 0
					}
				})
				return
			},
			async sendDataUDP() {
				if (this.currents === 1 || --this.sendRerty.times === 0) {
					return
				}
				const $t = this
				this.content = '正在配网……'
				// 这是发送密码的内容。要维护一个定时器，如果每两秒不回复，那么要再发
				const msgData = {
					"cmdType": 1,
					"ssid": this.targetWifiInfo.SSID,
					"password": this.targetWifiInfo.password
				}
				this.udp.send({
					address: '192.168.4.1',
					port: 8266,
					message: JSON.stringify(msgData)
				})
				// 如果times==0，那么不需要再重试
				if (this.sendRerty.times !== 0) {
					setTimeout(() => {
						$t.sendDataUDP()
					}, 2000)
				}
				return
			},
			
			linkToHome() {
				uni.reLaunch({
					url: '/pages/configWiFi/tipspage/tipspage'
				})
			},
			linkToWifiForm() {
				uni.navigateTo({
					url: '/pages/configWiFi/formpage/formpage'
				})
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	.uni-page {
		height: 100vh;
		background-color: #FFFFFF;
	}

	.page-main {
		padding-top: 40rpx;

		.main-box {
			padding: 60rpx 40rpx 0;
		}
	}

	.center_img {
		width: 280rpx;
		height: 280rpx;
		margin: 100rpx auto 80rpx;
	}

	.imgs {
		display: flex;
	}

	.gundong {
		display: flex;
		align-items: center;
		justify-content: center;

		.msg {
			font-size: 30rpx;
		}
	}

	.buttonst {
		margin: 120rpx 60rpx 0;
	}

	.back-btn {
		display: block;
		margin-bottom: 40rpx;
	}

	.div_top {
		height: 300px;
	}

	.iconst {
		padding: 5px;
	}

	.iconste {
		padding: 5px;
	}
</style>
